package com.gitee.ipo.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.ipo.system.entity.report.IpoReportInfo;
import com.gitee.ipo.system.mapper.IpoReportInfoMapper;
import com.gitee.ipo.system.service.IpoReportInfoService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 行业报告
 */
@Service
public class IpoReportInfoServiceImpl extends ServiceImpl<IpoReportInfoMapper, IpoReportInfo> implements IpoReportInfoService {


    /**
     * 源文件下载
     *
     * @param id
     * @param response
     * @param request
     */
    @Override
    public void downloadFile(Long id, HttpServletResponse response, HttpServletRequest request) {
        IpoReportInfo reportInfo = getById(id);
        try {
            //获取文件名称
            String fileName = reportInfo.getTitle() + ".doc";
            // 浏览器
            String browser = request.getHeader("User-Agent").toUpperCase();

            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + browserFileName(browser, fileName));
            //开始下载
            BufferedInputStream is = new BufferedInputStream(new URL("http://www.csrc.gov.cn/csrc/c100089/c6553564/6553564/files/鼎镁新材料科技股份有限公司首发申请文件反馈意见.doc").openStream());
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[1024];
            int len;
            while ((len = is.read(buff, 0, buff.length)) != -1) {
                out.write(buff, 0, len);
            }
            is.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String browserFileName(String browser, String fileName) {
        String result = "";
        try {
            if (browser.contains("CHROME")) {
                // 谷歌
                result = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
            } else if ((browser.contains("FIREFOX"))) {
                // firefox浏览器
                result = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
            } else if (browser.contains("MSIE") || browser.contains("TRIDENT")) {
                // IE浏览器
                result = URLEncoder.encode(fileName, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
